import { Category } from '../category/category-model.js';
import { ProductList } from "../product/list-model.js";
import { Product } from '../product/product-model.js';
import { Cart } from '../cart/cart-model.js';
var category = new Category();
var productlist = new ProductList();
var product = new Product();
var cart = new Cart();

Page({
  data: {
    currentMenuIndex: 0,
    sonIndex: '',
    loadingHidden: false,
    hiddenAttrBox: true,
    show_type: 2,  //显示模式 1传统模式 2一级分类模式,3左边大类，右边二级+商品
    type_id: '',
    pid: '',
    page:1,
    params:{},
    isLine:true,
    leftScroll:0
  },
  onLoad: function () {
    this._loadData();
  },

  /*加载所有数据*/
  _loadData: function (callback) {
    var that = this;
    var param = {
      num: 100000,
      shop_id: 1
    }
    category.getproductType(100000, (data) => {
      this.setData({
        //show_type: data.show_type ? data.show_type : 2,
        show_type: 3,
        categoryData: data.items,
        loadingHidden: true
      })
      that.product();
    });
  },
  /*加载商品数据*/
  product: function () {
    var that = this;
    var sort = 'id';
    this.data.params = {
      type_id: this.data.type_id ? this.data.type_id : this.data.pid
    }
    if (this.data.loading) {
      return false;
    }
    this.data.loading = true;
    productlist.getProductData(this.data.page, sort, this.data.params, (data) => {
      this.data.loading = false;
      wx.hideLoading();
      that.setData({
        productData: data.items,
        pageCount: data._meta.pageCount,
        loadingHidden: true,
      })
      if (data._meta.pageCount == 1) {
        that.setData({
          searchLoading: false,
          noMore: true,
        })
      }
    })
  },
  reset: function () {
    this.data.page = 1;
    this.data.productData = [];
  },
  /*切换分类*/
  changeCategory: function (event) {
    var that = this,
    index = category.getDataSet(event, 'index');
    this.data.pid = event.currentTarget.dataset.id;
    this.data.type_id = '';
    that.reset();
    that.product();
    wx.showLoading({
      title: '加载中...',
    })
    that.setData({
      currentMenuIndex: index,
      sonIndex: '',
      toView: "category_id_" + that.data.categoryData[index].category_id
    });
  },
  /*切换二级分类*/
  change: function (event) {
    var that = this,
      index = category.getDataSet(event, 'index');
    var id = event.currentTarget.dataset.id;
    this.data.type_id = id;
    that.reset();
    that.product();
    wx.showLoading({
      title: '加载中...',
    })
    let ac = index > 2 ? index -2 : 0;
    that.setData({
      sonIndex: index,
      isLine: true,
      childView: 'type_child_id_' + ac
    });
  },
  open:function(){
    this.setData({
      isLine : !this.data.isLine
    })
  },
  /*切换商品属性*/
  onTabsItemTap: function (event) {
    var productDetail = this.data.productDetail;
    var data = product.changAttr(event, productDetail);
    this.setData({
      'productDetail.attributes': data
    });
    var skusindex = product.changProductinf(this.data.productDetail);
    if (skusindex != undefined) {
      this.setData({
        'allselect': 1,
        'skus': this.data.productDetail.skus[skusindex],
      });

    } else {
      this.setData({
        'allselect': 0,
      });
    }

  },

  /*调整商品数目*/
  onChangeCountsTap: function (event) {
    var maxCount, selected_skus_id;
    if (this.data.allselect == "0") {
      maxCount = this.data.productDetail.product.stock
    } else if (this.data.allselect == "1") {
      maxCount = this.data.skus.stock;
    }
    var currentNum = product.changeCounts(event, this.data.productCounts);
    if (currentNum > maxCount) {
      currentNum = maxCount;
      if (maxCount == 0) {
        currentNum = 1;
        wx.showToast({
          title: '暂无库存~',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '大于库存~',
          icon: 'none',
          duration: 2000
        })
      }
    }
    this.setData({
      'productCounts': currentNum
    })
  },
  //手动输入商品数目
  countChange: function (e) {
    var currentNum = e.detail.value;
    var maxCount, selected_skus_id;
    if (this.data.allselect == "0") {
      maxCount = this.data.productDetail.product.stock
    } else if (this.data.allselect == "1") {
      maxCount = this.data.skus.stock;
    }
    if (currentNum && currentNum < 1) {
      currentNum = 1;
      wx.showToast({
        title: '数量必须是正整数',
        icon: 'none',
        duration: 2000
      })
    }
    if (currentNum > maxCount) {
      currentNum = maxCount;
      if (maxCount == 0) {
        currentNum = 1;
        wx.showToast({
          title: '暂无库存~',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '大于库存~',
          icon: 'none',
          duration: 2000
        })
      }
    }
    this.setData({
      'productCounts': currentNum
    })
  },

  //加入购物车或立即购买
  onAddingToCartTap: function (event) {
    var flag = product.getDataSet(event, 'from')
    if (product.isSelectAll(this.data.productDetail).skustr) {
      this.setData({
        'selectLabel': product.isSelectAll(this.data.productDetail).selectLabel
      })
      var params = {
        'sku_id': product.isSelectAll(this.data.productDetail).skustr,
        'num': this.data.productCounts ? this.data.productCounts : 1,
        'prom_type': this.data.prom_type,
        'prom_id': this.data.prom_id,
      }
      if (flag == 'cart') {
        params.type = 0;
      } else {
        params.type = 1;
      }
      cart.addProduct2Cart(params, (data) => {
        var status = data.status,
          msg = data.msg;
        if (status == 1 && flag == 'cart') {
          var cart = wx.getStorageSync('cart');
          if (!cart) {
            cart = 0;
          }
          cart++;
          wx.setTabBarBadge({
            index: 2,   //代表哪个tabbar（从0开始）
            text: cart + ''		//显示的内容
          })
          wx.setStorageSync('cart', cart);
          this.cancelattrbox();
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
          this.setData({
            'productCounts': 1,
          });
        } else if (status == 1 && flag == 'buy') {
          wx.navigateTo({
            url: '../order/order?from=buy' + '&id=' + msg
          })
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
        }

      });
    } else {
      this.setData({
        unselectLabel: product.isSelectAll(this.data.productDetail).unselectLabel,
        'selectLabel': false
      })
      if (this.data.productDetail.product.stock == 0) {
        wx.showToast({
          title: '暂无库存！',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '请选择  ' + product.isSelectAll(this.data.productDetail).unselectLabel,
          icon: 'none',
          duration: 2000
        })
      }
    }

  },
  //商品属性弹出框显示
  showattrbox: function (e) {
    var product_id = e.currentTarget.dataset.id;
    this.setData({
      'hiddenAttrBox': !this.data.hiddenAttrBox,
      'productCounts': 1,

    });
    product.getSkuData(product_id, (sku) => {
      this.setData({
        'productDetail': sku,
        'allselect': 0
      });
    })
  },
  //商品属性弹出框关闭
  cancelattrbox: function (e) {
    if (product.isSelectAll(this.data.productDetail).unselectLabel) {
      this.setData({
        'hiddenAttrBox': true,
        'unselectLabel': product.isSelectAll(this.data.productDetail).unselectLabel,
      })
    } else {
      this.setData({
        'hiddenAttrBox': true,
      })
    }
  },
  /*跳转到商品列表页*/
  onProductListItemTap: function (event) {
    var id = category.getDataSet(event, 'id');
    var hot = category.getDataSet(event, 'hot');
    // var child = category.getDataSet(event, 'child');
    wx.navigateTo({
      url: '../product/list?id=' + id + '&hot=' + hot
    })
  },

  /*跳转到商品详情*/
  onProductsItemTap: function (event) {
    var id = event.currentTarget.dataset.id;
    var skuid = event.currentTarget.dataset.skuid;
    var uid = wx.getStorageSync('uid');
    if (skuid) {
      wx.navigateTo({
        url: '../product/product?id=' + id + '&skuid=' + skuid
      })
    } else {
      wx.navigateTo({
        url: '../product/product?id=' + id
      })
    }
  },
  /*搜索*/
  showInput: function () {
    wx.navigateTo({
      url: '../product/list?search=1'
    })
  },

  //滚动加载
  lower: function (e) {
    var page = parseInt(this.data.page) + 1;
    if (page <= this.data.pageCount) {
      this.setData({
        searchLoading: true,
      })
      productlist.getProductData(page, '', this.data.params, (data) => {
        this.scrollLoadData(data, page);
      })
    } else {
      this.setData({
        noMore: true,
      })
    }
  },
  scrollLoadData: function (data, page) {
    var productData = this.data.productData;
    productData = productData.concat(data.items)
    this.setData({
      productData: productData,
      page: page,
    })
    if (page == this.data.pageCount) {
      this.setData({
        searchLoading: false,
        noMore: true,
      })
    }
  },
})